import { DOCUMENT } from '@angular/common';
import { Directive, ElementRef, EventEmitter, Inject, Input, OnChanges, Output, Renderer2, SimpleChanges } from '@angular/core';

@Directive({
  selector: '[appClickoutside]'
})
export class ClickoutsideDirective implements OnChanges {
  private handleClick!: () => void;

  @Input() bindFlag = false;

  @Output() onClickOutSide = new EventEmitter<HTMLElement>();
  constructor(
    private el: ElementRef,
    private rd: Renderer2,                  // 操作doc方法
    @Inject(DOCUMENT) private doc: Document
  ) {
  }
  ngOnChanges(changes: SimpleChanges): void {
    if(changes['bindFlag'] && !changes['bindFlag'].firstChange){
      if (this.bindFlag){
        this.handleClick = this.rd.listen(this.doc, 'click', evt =>{
          const isContain = this.el.nativeElement.contains(evt.target)
          const target = evt.target
          // 点击当前 el 元素外部就发送方法
          if(!isContain){
            this.onClickOutSide.emit(target)
          }
        })
      }else{
        this.handleClick()
      }
    }
  }

}
